package com.yyy.tcc.dao;

import com.yyy.tcc.entity.TransferTransaction;
import javax.sql.DataSource;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TransferTransactionDao {
    private DataSource dataSource;

    public TransferTransactionDao(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public boolean createTransaction(String transactionId, String fromUserId, String toUserId, BigDecimal amount) throws SQLException {
        String sql = "INSERT INTO transfer_record (transaction_id, from_user_id, to_user_id, amount, status) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, transactionId);
            ps.setString(2, fromUserId);
            ps.setString(3, toUserId);
            ps.setBigDecimal(4, amount);
            ps.setString(5, "TRYING");
            return ps.executeUpdate() > 0;
        } catch (SQLException e) {
            if (e.getErrorCode() == 1062) { // MySQL重复键错误
                return false;
            }
            throw e;
        }
    }

    public TransferTransaction getByTransactionId(String transactionId) throws SQLException {
        String sql = "SELECT * FROM transfer_record WHERE transaction_id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, transactionId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                TransferTransaction transaction = new TransferTransaction();
                transaction.setTransactionId(rs.getString("transaction_id"));
                transaction.setFromUserId(rs.getString("from_user_id"));
                transaction.setToUserId(rs.getString("to_user_id"));
                transaction.setAmount(rs.getBigDecimal("amount"));
                transaction.setStatus(rs.getString("status"));
                return transaction;
            }
            return null;
        }
    }

    public void updateStatus(String transactionId, String status) throws SQLException {
        String sql = "UPDATE transfer_record SET status = ? WHERE transaction_id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, status);
            ps.setString(2, transactionId);
            ps.executeUpdate();
        }
    }
}
